package com.smart.register.service.redis;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class ReidsTemplate {
	private static final Logger logger = LoggerFactory.getLogger(ReidsTemplate.class);
	private Jedis conn = null;
	private Properties prop;
	private JedisPool pool = null;
	
	public ReidsTemplate(){}
	
	public ReidsTemplate(Properties prop){
		this.prop = prop;
		init();
	}
	
	private void init(){
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(200);
	    config.setMaxIdle(50);
	    config.setMinIdle(16);
	    config.setMaxWaitMillis(10000);//最大等待wait时间
	    config.setTestOnBorrow(true);//获得一个jedis实例的时候是否检查连接可用性（ping())
	    config.setTestOnReturn(true);//return 一个jedis实例给pool时，是否检查连接可用性（ping())
	    config.setTestWhileIdle(true);////Idle时进行连接扫描
	    config.setTimeBetweenEvictionRunsMillis(30000);//表示idle object evitor两次扫描之间要sleep的毫秒数
	    config.setNumTestsPerEvictionRun(10);//表示idle object evitor每次扫描的最多的对象数
	    config.setMinEvictableIdleTimeMillis(60000);//表示一个对象至少停留在idle状态的最短时间，然后才能被idle object evitor扫描并驱逐；这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
		pool = new JedisPool(config, prop.getProperty("redis.host"), Integer.parseInt(prop.getProperty("redis.port", "6379")), 0);
	}

	public <T> T execute(RedisCallback<T> action) {
		conn = pool.getResource();
		try {
			return action.doInRedis(conn);
		} catch (Exception e) {
			logger.debug(">> Excute Exception !", e);
		}finally{
			if(conn != null){
				conn.close();
			}
		}
		return null;
	}
}
